package com.huawang.mdesign.model.service.util;

import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import org.jetbrains.annotations.NotNull;

import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class RSAUtils {

    private static final String RSA = "RSA";

    private RSAUtils() {
        throw new IllegalStateException("Utility class");
    }

    public static String convertKeyToString(Key key){
        return  Base64.getEncoder().encodeToString(key.getEncoded());
    }

    @NotNull
    public static PublicKey convertStringToPublicKey(String key) throws NoSuchAlgorithmException, InvalidKeySpecException, IllegalArgumentException  {
        byte[] keyBytes;
        keyBytes = Base64.getDecoder().decode(key);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(RSA);
        return keyFactory.generatePublic(keySpec);
    }

    @NotNull
    public static PrivateKey convertStringToPrivateKey(String key) throws NoSuchAlgorithmException, InvalidKeySpecException, IllegalArgumentException  {
        byte[] keyBytes;
        keyBytes = Base64.getDecoder().decode(key);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(RSA);
        return keyFactory.generatePrivate(keySpec);
    }

    @NotNull
    public static String encryptData(String modelId, PublicKey publicKey) {
        RSA rsa = new RSA(null, publicKey);
        return rsa.encryptBase64(modelId, KeyType.PublicKey);
    }

    @NotNull
    public static String decryptData(String encryptedData, PrivateKey privateKey) {
        RSA rsa = new RSA(privateKey, null);
        return rsa.decryptStr(encryptedData, KeyType.PrivateKey);
    }

    @NotNull
    public static KeyPair generateKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        // 随机生成密钥对
        SecureRandom secureRandom = new SecureRandom();
        keyPairGenerator.initialize(2048, secureRandom);
        return keyPairGenerator.generateKeyPair();
    }
}
